<template>
  <div class="divBox">
    <el-card class="box-card boxCard" shadow="hover" :body-style="{ paddingBottom: 0, borderBottom: 0 }">
      <template v-slot:header class="clearfix">
        <el-tabs v-model="currentTab" :before-leave="beforeLeave">
          <el-tab-pane v-for="(item, index) in tabPaneVal" :key="item" :label="item" :name="index.toString()"></el-tab-pane>
        </el-tabs>
      </template>

      <el-form ref="formValidate" v-loading="fullscreenLoading" :rules="ruleValidate" :model="formValidate" size="small" class="formValidate mt20" label-width="120px" @submit.native.prevent>
        <!--商品信息【start】-->
        <el-row v-show="currentTab == 0" :gutter="24">
          <el-col v-bind="grid2">
            <el-form-item label="商品名称：" prop="storeName">
              <el-input v-model="formValidate.storeName" :disabled="isDisabled" maxlength="249" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>

          <el-col v-bind="grid2">
            <el-form-item label="商品分类：" prop="cateIds">
              <el-cascader
                v-model="formValidate.cateIds"
                :options="merCateList"
                :props="props2"
                clearable
                style="width: 100%"
                :show-all-levels="false"
                :disabled="isDisabled"
              />
            </el-form-item>
          </el-col>

          <el-col v-bind="grid2">
            <el-form-item label="单位：" prop="unitName">
              <el-input v-model="formValidate.unitName" :disabled="isDisabled" placeholder="请输入单位" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品描述：" prop="storeInfo">
              <el-input v-model="formValidate.storeInfo" :disabled="isDisabled" type="textarea" maxlength="250" :rows="3" placeholder="请输入商品描述" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品封面图：" prop="image">
              <div class="upLoadPicBox cover-box" :disabled="isDisabled">
                <div @click="modalPicTap('1')" v-if="formValidate.image" class="coverImg"><img v-lazy="$uploadURL(formValidate.image)"></div>
                <div @click="modalPicTap('1')" v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品轮播图：" prop="sliderImages">
              <div class="acea-row">
                <div
                  v-for="(item,index) in formValidate.sliderImages"
                  :key="index"
                  class="pictrue"
                  draggable="true"
                  @dragstart="handleDragStart($event, item)"
                  @dragover.prevent="handleDragOver($event, item)"
                  @dragenter="handleDragEnter($event, item, 'slider')"
                  @dragend="handleDragEnd($event, item)"
                >
                  <img v-lazy="$uploadURL(item)">
                  <i v-if="!isDisabled" class="el-icon-error btndel" @click="handleRemove(index)" />
                </div>
                <div v-if="formValidate.sliderImages.length < 10 && !isDisabled" class="upLoadPicBox" @click="modalPicTap('2')">
                  <div class="upLoad">
                    <i class="el-icon-camera cameraIconfont" />
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品规格：" props="specType" class="specType">
              <el-radio-group v-model="formValidate.specType" :disabled="isDisabled" @change="onChangeSpec(formValidate.specType)">
                <el-radio :label="false" class="radio">单规格</el-radio>
                <el-radio :label="true">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!--多规格添加【start】-->
          <el-col v-if="formValidate.specType && !isDisabled" :span="24" class="noForm">
            <el-form-item label="选择规格：">
              <div class="acea-row choiceFormat">
                <el-select v-model="formValidate.selectRule">
                  <el-option v-for="item in ruleList" :key="item.id" :label="item.ruleName" :value="item.id" />
                </el-select>
                <el-button type="primary" class="mr20" @click="confirm">确认</el-button>
                <el-button @click="addRule" style="margin-left: 0px;">添加规格</el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <draggable
                class="dragArea list-group"
                :list="formValidate.attr"
                group="peoples"
                handle=".move-icon"
                :move="checkMove"
                @end="end"
              >
                <div v-for="(item, index) in formValidate.attr" :key="index" class="type-tag mb15">
                  <div class="move-icon scopeType-tag-svg">
                    <svg-icon icon-class="dashboard" class-name="custom-class" />
                  </div>
                  <div class="scopeType-tag" :class="moveIndex === index ? 'borderStyle' : ''">
                    <div class="acea-row row-middle">
                      <span class="mr5">{{ item.attrName }}</span>
                      <i class="el-icon-circle-close" @click="handleRemoveAttr(index)" />
                    </div>
                    <div class="rulesBox">
                      <draggable
                        :list="item.attrValue"
                        handle=".drag"
                      >
                        <el-tag
                          v-for="(j, indexn) in item.attrValue"
                          :key="indexn"
                          closable
                          size="medium"
                          :disable-transitions="false"
                          class="drag mb5 mr10"
                          @close="handleClose(item.attrValue, indexn)"
                        >
                          {{ j }}
                        </el-tag>
                      </draggable>
                      <el-input
                        v-if="item.inputVisible"
                        ref="saveTagInput"
                        v-model="item.attrValue.attrsVal"
                        class="input-new-tag"
                        size="small"
                        @keyup.enter.native="$event.target.blur"
                        @blur="createAttr(item.attrValue.attrsVal, index)"
                      />

                      <!--<el-input
                        v-if="item.inputVisible"
                        ref="saveTagInput"
                        placeholder="请输入内容"
                        v-model="item.attrValue.attrsVal"
                        class="input-new-tag"
                        size="small"
                        @keyup.enter.native="$event.target.blur"
                        @blur.prevent="createAttr(item.attrValue.attrsVal, index)"
                      >
                        <template v-slot:append>
                          <el-button type="primary" @click.native.stop="clearAttr(index, $event)">取消</el-button>
                        </template>
                      </el-input>-->

                      <el-button v-else class="button-new-tag" @click="showInput(item)">+ 添加</el-button>
                    </div>
                  </div>
                </div>
              </draggable>
            </el-form-item>

            <el-col v-if="isBtn">
              <el-col :xl="6" :lg="8" :md="9" :sm="12" :xs="24">
                <el-form-item label="规格：">
                  <el-input v-model="formDynamic.attrsName" placeholder="请输入规格" />
                </el-form-item>
              </el-col>
              <el-col :xl="6" :lg="8" :md="9" :sm="12" :xs="24">
                <el-form-item label="规格值：">
                  <el-input v-model="formDynamic.attrsVal" placeholder="请输入规格值" />
                </el-form-item>
              </el-col>
              <el-col :xl="12" :lg="8" :md="6" :sm="24" :xs="24">
                <el-form-item label-width="80" class="noLeft">
                  <el-button type="primary" class="mr15" @click="createAttrName">确定</el-button>
                  <el-button @click="offAttrName">取消</el-button>
                </el-form-item>
              </el-col>
            </el-col>
            <el-form-item v-if="!isBtn">
              <el-button type="primary" icon="md-add" class="mr5" @click="addBtn">添加新规格</el-button>
              <el-button type="success" icon="md-add" class="mr15" @click="generate(formValidate.attr)">立即生成</el-button>
            </el-form-item>
          </el-col>
          <!--批量设置【start】-->
          <el-col v-if="formValidate.attr.length > 0 && formValidate.specType && generateData && !isDisabled" :span="24" class="noForm">
            <el-form-item label="批量设置：" class="labeltop disLabelmoren">
              <el-table :data="oneFormBatch" border class="tabNumWidth" size="mini">

                <el-table-column align="center" label="图片" min-width="80">
                  <template slot-scope="scope">
                    <div class="upLoadPicBox" @click="modalPicTap('1', 'duo')">
                      <div v-if="scope.row.image" class="pictrue tabPic"><img v-lazy="$uploadURL(scope.row.image)"></div>
                      <div v-else class="upLoad tabPic">
                        <i class="el-icon-camera cameraIconfont" />
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  v-for="(item, key) in attrValue"
                  :key="key"
                  :label="formThead[key].title"
                  align="center"
                  min-width="140"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row[key]" :type="formThead[key].title === '商品编号' ? 'text': 'number'" :min="0" class="priceBox" />
                  </template>
                </el-table-column>

                <template v-if="formValidate.isSub">
                  <el-table-column align="center" label="一级返佣(元)" min-width="120">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.brokerage" type="number" :min="0" :max="scope.row.price" class="priceBox" />
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="二级返佣(元)" min-width="120">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.brokerageTwo" type="number" :min="0" :max="scope.row.price" class="priceBox" />
                    </template>
                  </el-table-column>
                </template>

                <el-table-column align="center" label="操作" min-width="80">
                  <template>
                    <el-button type="text" class="submission" @click="batchAdd">批量添加</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
          <!--批量设置【end】-->
          <el-col :span="24">
            <!--单规格表格【start】-->
            <el-form-item v-if="formValidate.specType === false">
              <el-table :data="OneattrValue" border class="tabNumWidth" size="mini">
                <el-table-column align="center" label="图片" min-width="80">
                  <template slot-scope="scope">
                    <div class="upLoadPicBox" @click="modalPicTap('1', 'dan')">
                      <div v-if="scope.row.image" class="pictrue tabPic"><img v-lazy="$uploadURL(scope.row.image)"></div>
                      <div v-else class="upLoad tabPic">
                        <i class="el-icon-camera cameraIconfont" />
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <!--表格遍历【start】-->
                <el-table-column v-for="(item,iii) in attrValue" :key="iii" :label="formThead[iii].title" align="center" min-width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row[iii]" :disabled="isDisabled" :type="formThead[iii].title==='商品编号'?'text':'number'" :min="0" class="priceBox" />
                  </template>
                </el-table-column>
                <!--表格遍历【end】-->

                <template v-if="formValidate.isSub">
                  <el-table-column align="center" label="一级返佣(元)" min-width="120">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.brokerage" :disabled="isDisabled" type="number" :min="0" class="priceBox" />
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="二级返佣(元)" min-width="120">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.brokerageTwo" :disabled="isDisabled" type="number" :min="0" class="priceBox" />
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </el-form-item>
            <!--单规格表格【end】-->

            <!--多规格表格【start】-->
            <el-form-item v-if="formValidate.attr.length > 0 && formValidate.specType && generateData" :class="isDisabled ? 'disLabel' : 'disLabelmoren'" label="商品属性：" class="labeltop">
              <el-table :data="ManyAttrValue" border class="tabNumWidth" size="mini">
                <!--渲染的表格数据【start】  注：Vue遍历对象第二个参数为键名（也就是可以key）-->
                <template v-if="manyTabDate">
                  <el-table-column
                    v-for="(item, key) in manyTabDate"
                    :key="key"
                    :label="manyTabTit[key].title"
                    align="center"
                    min-width="80"
                  >
                    <template slot-scope="{ row }">
                      <span class="priceBox" v-text="row[key]" />
                    </template>
                  </el-table-column>
                </template>
                <!--渲染的表格数据【end】-->

                <!--渲染图片表格的数据【start】-->
                <el-table-column align="center" label="图片" min-width="80">
                  <template slot-scope="scope">
                    <div class="upLoadPicBox" @click="modalPicTap('1', 'duoTable', scope.$index)">
                      <div v-if="scope.row.image" class="pictrue tabPic"><img v-lazy="$uploadURL(scope.row.image)"></div>
                      <div v-else class="upLoad tabPic">
                        <i class="el-icon-camera cameraIconfont" />
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <!--渲染图片表格的数据【end】-->

                <!--渲染固定表格的数据【start】-->
                <el-table-column
                  v-for="(item, key) in attrValue"
                  :key="key"
                  align="center"
                  :label="formThead[key].title"
                  min-width="140"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row[key]" :disabled="isDisabled" :type="formThead[key].title === '商品编号' ? 'text': 'number'" :min="0" class="priceBox" />
                    <!--<el-input-number v-model="scope.row[key]" controls-position="right" :min="0" :disabled="isDisabled"></el-input-number>-->
                  </template>
                </el-table-column>
                <!--渲染固定表格的数据【end】-->

                <el-table-column v-if="formValidate.isSub" align="center" label="一级返佣(元)" min-width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.brokerage" :disabled="isDisabled" type="number" :min="0" :max="scope.row.price" class="priceBox" />
                  </template>
                </el-table-column>
                <el-table-column v-if="formValidate.isSub" align="center" label="二级返佣(元)" min-width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.brokerageTwo" :disabled="isDisabled" type="number" :min="0" :max="scope.row.price" class="priceBox" />
                  </template>
                </el-table-column>

                <el-table-column v-if="!isDisabled" key="3" align="center" label="操作" min-width="80">
                  <template slot-scope="scope">
                    <el-button type="text" class="submission" @click="deleteAttrTable(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <!--多规格表格【end】-->
          </el-col>
          <!--多规格添加【end】-->
        </el-row>
        <!--商品信息【end】-->

        <!--商品详情【start】-->
        <el-row v-show="currentTab == 1 && !isDisabled">
          <el-col :span="24">
            <el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
              <el-form-item label="商品详情：" prop="content" class="detail">
                <ueditor-from v-model="formValidate.content" :content="formValidate.content" @input="editorInput"></ueditor-from>
              </el-form-item>
            </el-col>
            <el-col :xs="4" :sm="24" :md="24" :lg="8" :xl="8">
              <div class="iframe hidden-md-and-down">
                <div class="title">详情预览</div>
                <div class="content" v-html="formValidate.content"></div>
              </div>
            </el-col>
          </el-col>
        </el-row>
        <el-row v-show="currentTab == 1 && isDisabled">
          <el-col :span="24">
            <el-form-item label="商品详情：">
              <span v-html="formValidate.content || '无'" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--商品详情【end】-->

        <!--其他设置【start】-->
        <el-row v-show="currentTab == 2">
          <el-col :span="24">
            <el-col v-bind="grid">
              <el-form-item label="排序：">
                <el-input-number v-model="formValidate.sort" :max="9999" :min="0" placeholder="请输入排序" :disabled="isDisabled" />
              </el-form-item>
            </el-col>
            <el-col v-bind="grid">
              <el-form-item label="积分：">
                <el-input-number v-model="formValidate.giveIntegral" :min="0" placeholder="请输入积分" :disabled="isDisabled" />
              </el-form-item>
            </el-col>
            <!--<el-col v-bind="grid">
              <el-form-item label="销量：">
                <el-input-number v-model="formValidate.sales" :min="0" placeholder="销量" :disabled="isDisabled" style="width: auto;" />
              </el-form-item>
            </el-col>-->
            <el-col v-bind="grid">
              <el-form-item label="虚拟销量：">
                <el-input-number v-model="formValidate.ficti" :min="0" placeholder="虚拟销量" :disabled="isDisabled" />
              </el-form-item>
            </el-col>
            <!--<el-col v-bind="grid">
              <el-form-item label="浏览量：">
                <el-input-number v-model="formValidate.browse" :min="0" placeholder="浏览量" :disabled="isDisabled" style="width: auto;" />
              </el-form-item>
            </el-col>-->
          </el-col>
          <el-col :span="24">
            <el-col v-for="(item, index) in recommend" :key="index" v-bind="grid">
              <el-form-item :label="item.name">
                <el-radio-group v-model="checkboxGroup[item.key]" size="small" :disabled="isDisabled">
                  <el-radio :label="0">{{ item.label[1] }}</el-radio>
                  <el-radio :label="1" class="radio">{{ item.label[0] }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col v-if="formValidate.activity.length > 0" :span="24">
            <el-form-item label="活动优先级：">
              <div class="color-list acea-row row-middle">
                <div
                  v-for="item in formValidate.activity"
                  :key="item"
                  :disabled="isDisabled"
                  class="color-item"
                  :class="activity[item]"
                  draggable="true"
                  @dragstart="handleDragStart($event, item)"
                  @dragover.prevent="handleDragOver($event, item)"
                  @dragenter="handleDragEnter($event, item)"
                  @dragend="handleDragEnd($event, item)"
                >{{ item }}</div>
                <div class="tip">可拖动按钮调整活动的优先展示顺序</div>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid">
            <el-form-item v-if="formValidate.createDateUTC" label="创建时间：">
              <el-input v-model="formValidate.createDateUTC" :disabled="true" placeholder="创建时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--其他设置【end】-->

        <el-form-item>
          <el-button v-show="currentTab > 0" type="primary" class="submission subCurLeft mr10" @click="handleSubmitUp">上一步</el-button>
          <el-button v-show="currentTab < tabPaneVal.length - 1" type="primary" class="submission subCurLeft mr10" @click="handleSubmitNest('formValidate', )">下一步</el-button>
          <el-button v-show="(Number(currentTab) === tabPaneVal.length - 1 || $route.params.id) && !isDisabled" type="primary" class="submission subCurLeft" @click="handleSubmit('formValidate')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import ueditorFrom from '@/components/ueditorFrom';
import draggable from 'vuedraggable';
import {
  productInfoApi
} from '@/api/product';
import {
  mapGetters
} from 'vuex';
import {
  categoryApi,
  templateListApi,
  productCreateApi,
  productUpdateApi
} from '@/api/store';

const defaultObj = {
  content: '',
  cateIds: [], // 商品分类ID
  cateId: '',
  storeName: '', // 商品名称
  unitName: '', // 单位
  storeInfo: '', // 商品简介
  image: '', // 封面图
  sliderImage: '',
  sliderImages: [], // 轮播图
  specType: false, // 规格
  selectRule: [], // 规格添加下拉框
  attr: [], // 规格参数
  attrValue: [
    {
      image: '',
      price: 0,
      costPrice: 0,
      marketPrice: 0,
      stock: 0,
      weight: 0,
      volume: 0
    }
  ],
  isSub: false, // 返佣金
  isShow: 0,
  isDel: 0,
  sort: 0, // 排序
  giveIntegral: 0, // 积分
  sales: 0, // 销量
  ficti: 0, // 虚拟销量
  browse: 0, // 浏览量
  activity: [],
  createDateUTC: '' // 创建时间
}

const proOptions = [
  { name: '热卖单品：', key: 'isHot', label: ['开启', '关闭'] },
  { name: '精品推荐：', key: 'isBest', label: ['开启', '关闭'] },
  { name: '首发新品：', key: 'isNew', label: ['开启', '关闭'] },
  { name: '秒杀状态：', key: 'isSeckill', label: ['开启', '关闭'] },
  { name: '砍价状态：', key: 'isBargain', label: ['开启', '关闭'] }
]

// 批量设置表头
const objTitle = {
  price: {
    title: '售价'
  },
  marketPrice: {
    title: '原价'
  },
  costPrice: {
    title: '成本价'
  },
  stock: {
    title: '库存'
  },
  weight: {
    title: '重量（KG）'
  },
  volume: {
    title: '体积(m³)'
  }
}

export default {
  name: 'ProductAdd',
  components: {
    ueditorFrom,
    draggable
  },
  data() {
    return {
      // 双行
      grid2: {
        xl: 10,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24
      },
      // 单行
      grid: {
        xl: 8,
        lg: 8,
        md: 8,
        sm: 12,
        xs: 24
      },
      isDisabled: this.$route.params.isDisabled === '1',
      // tab切换
      currentTab: 0,
      // 全屏加载
      fullscreenLoading: false,
      // 表单
      formValidate: Object.assign({}, defaultObj),
      // 表头
      formThead: Object.assign({}, objTitle),
      // 单规格表格
      OneattrValue: [Object.assign({}, defaultObj.attrValue[0])],
      // 多规格表格
      ManyAttrValue: [Object.assign({}, defaultObj.attrValue[0])],
      // 表单验证
      ruleValidate: {
        storeName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { required: true, min: 0, max: 100, message: '商品名称最多为50个字符', trigger: 'blur' }
        ],
        unitName: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ],
        storeInfo: [
          { required: true, message: '请输入商品简介', trigger: 'blur' },
          { required: true, min: 0, max: 1500, message: '商品名称最多为50个字符', trigger: 'blur' }
        ],
        cateIds: [
          { required: true, message: '请选择商品分类', trigger: 'change', type: 'array', min: 1 }
        ],
        image: [
          { required: true, message: '请上传商品图', trigger: 'change' }
        ],
        sliderImages: [
          { required: true, message: '请选择商品轮播图', type: 'array', trigger: 'change' }
        ],
        content: []
      },
      // 商户分类筛选
      merCateList: [],
      // 商品分类的打开方式
      props2: {
        children: 'children',
        label: 'name',
        value: 'id',
        multiple: true,
        emitPath: false
      },
      // 规格添加下拉框的循环
      ruleList: [],
      isBtn: false,
      // 弹框规格数据
      formDynamics: {
        ruleName: '',
        ruleValue: []
      },
      // 规格数据
      formDynamic: {
        attrsName: [],
        attrsVal: ''
      },
      // 多规格开头渲染的表格数据
      manyTabDate: {},
      // 多规格标题
      manyTabTit: {},
      // 商品推荐
      checkboxGroup: {
        isHot: 0,
        isBest: 0,
        isNew: 0,
        isSeckill: 0,
        isBargain: 0
      },
      // 推荐
      recommend: proOptions,
      activity: { '默认': 'red', '秒杀': 'blue', '砍价': 'green', '拼团': 'yellow' },
      // 属性信息
      attrInfo: {},
      moveIndex: '',
      tempRoute: {},
      generateData: false,
      isDashboard: false
    }
  },
  computed: {
    ...mapGetters([
      'customRouter'
    ]),
    // 单规格表格数据
    attrValue() {
      const obj = Object.assign({}, defaultObj.attrValue[0])
      delete obj.image
      return obj
    },
    // 批量添加表格数据
    oneFormBatch() {
      const obj = [Object.assign({}, defaultObj.attrValue[0])]
      delete obj[0].barCode
      return obj
    },
    tabPaneVal() {
      return ['商品信息', '商品详情', '其他设置']
    }
  },
  watch: {
    currentTab(newV, oldV) {
      if (newV == 1) {
        this.$set(this.ruleValidate, 'content', [
          { required: true, message: '请输入商品详情', trigger: 'blur' }
        ]);
      } else if (newV == 0) {
        this.$set(this.ruleValidate, 'content', []);
      }
    }
  },
  mounted() {
    // 如果存在ID则处于编辑状态
    this.$nextTick(() => {
      this.$set(this.formValidate, 'sliderImages', [])
      if (this.$route.params.id) {
        this.setTagsViewTitle()
        this.getInfo()
      }
      // 获取商品分类
      this.getCategorySelect()
    })
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    editorInput(e) {
      this.$refs[`formValidate`].validateField('content');
    },
    formValidateMethod() {
      return new Promise((resolve, reject) => {
        this.$refs[`formValidate`].validate(async (valid) => {
          if (valid) {
            resolve(true);
          } else {
            const { storeName, unitName, storeInfo, cateIds, image, sliderImages, content } = this.formValidate;
            if (((!storeName || !unitName || !storeInfo || !cateIds.length || !image || !sliderImages.length) && (this.currentTab == 0)) || (this.currentTab == 1 && !content)) this.$message.warning('请填写完整商品信息！');
            reject(false);
          };
        });
      });
    },
    async beforeLeave(newIndex, oldIndex) {
      if (oldIndex > newIndex) return true;
      if (oldIndex && (oldIndex == 0 && this.currentTab == 0) || (oldIndex == 1 && this.currentTab == 1)) return await this.formValidateMethod();
    },
    // 封面图
    modalPicTap(tit, num, i) {
      const _this = this
      if (!this.isDisabled) {
        this.$modalUpload((data) => {
          if (tit === '1' && !num && this.formValidate.specType) {
            _this.formValidate.image = data[0].path
            if (!this.$route.params.id) {
              _this.oneFormBatch[0].image = data[0].path
              _this.ManyAttrValue.forEach((item) => {
                item.image = data[0].path
              })
            }
          } else if (tit === '2' && !num) {
            if (data.length > 10) this.$message.warning('最多选择10张图片！')
            if ((data.length + _this.formValidate.sliderImages.length) > 10) this.$message.warning('最多选择10张图片！')
            const list = []
            data.forEach((item, index) => {
              if (_this.formValidate.sliderImages.length + index + 1 <= 10) list.push(item.path)
            })
            _this.formValidate.sliderImages.push(...list);
            if (this.formValidate.sliderImages.length > 0) this.$refs['formValidate'].validateField('sliderImages');
          } else if (tit === '1' && !num) {
            _this.formValidate.image = data[0].path
            _this.OneattrValue[0].image = data[0].path
            if (_this.formValidate.image) this.$refs['formValidate'].validateField('image');
          } else if (tit === '1' && num === 'duoTable' && i !== '') {
            _this.ManyAttrValue[i].image = data[0].path
          } else if (tit === '1' && num === 'dan') {
            _this.OneattrValue[0].image = data[0].path
          } else if (tit === '1' && num === 'duo') {
            _this.oneFormBatch[0].image = data[0].path
          }
        }, tit, '', '上传商品图')
      }
    },
    // 生成
    generate(val) {
      if (this.formValidate.specType && this.formValidate.attr.length) {
        this.generateData = true
        const tmp = {}
        const tmpTab = {}
        this.formValidate.attr.forEach((item, index) => {
          tmp['value' + index] = { title: item.attrName }
          tmpTab['value' + index] = ''
        });
        this.ManyAttrValue = this.attrFormat(val)
        console.log(val);
        console.log(this.ManyAttrValue);
        this.ManyAttrValue.forEach((item, index) => {
          const key = Object.values(item.suk).sort().join('/')
          if (this.attrInfo[key]) this.ManyAttrValue[index] = this.attrInfo[key]
        })
        this.attrInfo = {}
        this.ManyAttrValue.forEach((val) => {
          this.attrInfo[Object.values(val.suk).sort().join('/')] = val
        });
        console.log(126, tmp, tmpTab);
        this.manyTabTit = tmp
        this.manyTabDate = tmpTab
        this.formThead = Object.assign({}, this.formThead, tmp)
      }
    },
    // 删除属性规格
    deleteAttrTable(index) {
      this.ManyAttrValue.splice(index, 1)
    },
    // 属性格式
    attrFormat(arr) {
      let data = []
      const res = []
      return format(arr)
      function format(arr) {
        if (arr.length > 1) {
          arr.forEach((v, i) => {
            if (i === 0) data = arr[i]['attrValue']
            const tmp = []
            data.forEach(function(vv) {
              arr[i + 1] && arr[i + 1]['attrValue'] && arr[i + 1]['attrValue'].forEach(g => {
                const rep2 = (i !== 0 ? '' : arr[i]['attrName'] + '_') + vv + '$&' + arr[i + 1]['attrName'] + '_' + g
                tmp.push(rep2)
                if (i === (arr.length - 2)) {
                  const rep4 = {
                    image: '',
                    price: 0,
                    costPrice: 0,
                    marketPrice: 0,
                    stock: 0,
                    weight: 0,
                    volume: 0
                  }
                  rep2.split('$&').forEach((h, k) => {
                    const rep3 = h.split('_')
                    if (!rep4['suk']) rep4['suk'] = []
                    rep4['suk'].push(rep3.length > 1 ? rep3[1] : '')
                  })
                  rep4['suk'].forEach((v, i) => {
                    rep4['value' + i] = v
                  })
                  rep4['suk'] = rep4['suk'].join(',')
                  res.push(rep4)
                }
              })
            })
            data = tmp.length ? tmp : []
          })
        } else {
          const dataArr = [];
          arr.forEach((v, k) => {
            v['attrValue'].forEach((vv, kk) => {
              res[kk] = {
                image: '',
                price: 0,
                costPrice: 0,
                marketPrice: 0,
                stock: 0,
                weight: 0,
                volume: 0,
                suk: vv
              };
              for (let key in { [v['attrName']]: vv }) {
                res[kk]['value' + 0] = res[kk].suk;
              };
            });
          });
          data.push(dataArr.join('$&'));
        };
        return res;
      };
    },
    // 设置视图标签
    setTagsViewTitle() {
      const title = this.$route.params.id && this.$route.params.isDisabled ? '商品详情' : '编辑商品-' + this.$route.params.id
      const route = Object.assign({}, this.tempRoute, { title: `${title}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    // 更改规格
    onChangeSpec(num) {
      if (num) this.productGetRule()
    },
    // 批量添加
    batchAdd() {
      for (const val of this.ManyAttrValue) {
        this.$set(val, 'image', this.oneFormBatch[0].image)
        this.$set(val, 'price', this.oneFormBatch[0].price)
        this.$set(val, 'costPrice', this.oneFormBatch[0].costPrice)
        this.$set(val, 'marketPrice', this.oneFormBatch[0].marketPrice)
        this.$set(val, 'stock', this.oneFormBatch[0].stock)
        this.$set(val, 'weight', this.oneFormBatch[0].weight)
        this.$set(val, 'volume', this.oneFormBatch[0].volume)
      }
    },
    // 商品分类API
    getCategorySelect() {
      categoryApi({ isShow: 1 }).then(res => {
        this.merCateList = this.filerMerCateList(res)
      })
    },
    filerMerCateList(treeData) {
      return treeData.map(item => {
        if (!item.children.length) {
          item.disabled = true
        }
        item.label = item.name
        return item
      })
    },
    // 确认添加规格数据
    confirm() {
      if (!this.formValidate.selectRule) {
        this.$message.warning('请选择商品规格属性')
      }
      console.log(this.ruleList, this.formValidate.selectRule);
      const data = []
      this.ruleList.forEach(item => {
        if (item.id === this.formValidate.selectRule) {
          item.ruleValue.forEach(rule => {
            data.push({
              attrName: rule.attrName,
              attrValue: rule.attrValue.split(',')
            });
          });
        };
      });
      this.formValidate.attr = data;
      console.log(this.formValidate.attr);
    },
    // 添加规格
    addRule() {
      const that = this
      this.$modalAttr(this.formDynamics, function() {
        that.productGetRule()
      });
    },
    // 获取商品属性模板
    productGetRule() {
      templateListApi().then(res => {
        res.data.forEach((item) => {
          item.ruleValue = JSON.parse(item.ruleValue)
        });
        this.ruleList = res.data
      });
    },
    // 取消添加规则名称
    offAttrName() {
      this.isBtn = false
    },
    // 添加规则名称
    createAttrName() {
      if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
        const data = {
          attrName: this.formDynamic.attrsName,
          attrValue: [
            this.formDynamic.attrsVal
          ]
        }
        this.formValidate.attr.push(data)
        const hash = {}
        this.formValidate.attr = this.formValidate.attr.reduce((item, next) => {
          if (hash[next.attrName]) {
            this.$message.warning('规格属性已存在!')
          } else {
            hash[next.attrName] = true && item.push(next)
          }
          return item
        }, [])
        this.clearAttrBlue()
        this.isBtn = false
      } else {
        this.$message.warning('请添加完整的规格！')
      }
    },
    // 添加新规格属性按钮
    addBtn() {
      this.isBtn = true
      this.clearAttrBlue()
    },
    // 清除新规格的值
    clearAttrBlue() {
      this.formDynamic.attrsName = ''
      this.formDynamic.attrsVal = ''
    },
    end() {
      this.moveIndex = ''
    },
    checkMove(evt) {
      this.moveIndex = evt.draggedContext.index
    },
    handleRemove(index) {
      this.formValidate.sliderImages.splice(index, 1)
    },
    // 删除整个规格
    handleRemoveAttr(index) {
      this.formValidate.attr.splice(index, 1)
    },
    // 规格删除属性
    handleClose(item, index) {
      item.splice(index, 1)
    },
    // 规格属性取消添加(以注释)
    clearAttr(index, e) {
      this.formValidate.attr[index].inputVisible = false
    },
    // 规格添加属性
    createAttr(num, idx) {
      if (num) {
        this.formValidate.attr[idx].attrValue.push(num)
        const hash = {}
        this.formValidate.attr[idx].attrValue = this.formValidate.attr[idx].attrValue.reduce((item, next) => {
          if (hash[next]) {
            this.$message.warning('规格属性已存在!')
          } else {
            hash[next] = true && item.push(next)
          }
          return item
        }, [])
        this.formValidate.attr[idx].inputVisible = false
      } else {
        this.$message.warning('请添加属性')
      }
    },
    // 规格添加
    showInput(item) {
      this.$set(item, 'inputVisible', true)
      this.$nextTick(() => {
        this.$refs.saveTagInput[0].focus()
      })
    },
    // 优先级移动
    handleDragStart(e, item) {
      if (!this.isDashboard) this.dragging = item
    },
    // 拖拽
    handleDragOver(e) {
      if (!this.isDisabled) e.dataTransfer.dropEffect = 'more'
    },
    // 手柄拖动拖拽图片
    handleDragEnter(e, item, drag) {
      if (!this.isDashboard) {
        if (drag === 'slider') {
          e.dataTransfer.effectAllowed = 'move'
          if (item === this.dragging) {
            return
          }
          const newItems = [...this.formValidate.sliderImages]
          const src = newItems.indexOf(this.dragging)
          const dst = newItems.indexOf(item)
          newItems.splice(dst, 0, ...newItems.splice(src, 1))
          this.formValidate.sliderImages = newItems
        } else {
          e.dataTransfer.effectAllowed = 'move'
          if (item === this.dragging) {
            return
          }
          const newItems = [...this.formValidate.activity]
          const src = newItems.indexOf(this.dragging)
          const dst = newItems.indexOf(item)
          newItems.splice(dst, 0, ...newItems.splice(src, 1))
          this.formValidate.activity = newItems
        }
      }
    },
    handleDragEnd($event, item) {
      if (!this.isDashboard) this.dragging = null
    },
    // 获取详细信息
    getInfo() {
      productInfoApi(this.$route.params.id).then(async res => {
        const info = res
        this.fullscreenLoading = false
        // 赋值
        this.formValidate = {
          content: info.content,
          cateIds: info.cate_Id.split(','), // 商品分类ID
          cateId: info.cate_Id,
          storeName: info.title, // 商品名称
          unitName: info.unitName, // 单位
          storeInfo: info.description, // 商品简介
          image: this.$selfUtil.setDomain(info.image), // 封面图
          price: info.price, // 商品价格
          marketPrice: info.marketPrice, // 市场价
          costPrice: info.costPrice, // 成本价
          sliderImage: info.sliderImage,
          sliderImages: info.sliderImage.split(','), // 轮播图
          specType: !!info.specType, // 规格
          selectRule: info.selectRule, // 规格添加下拉框
          attr: info.attrs, // 规格参数
          attrValue: [
            {
              image: '',
              marketPrice: 0,
              price: 0,
              costPrice: 0,
              stock: 0,
              weight: 0,
              volume: 0
            }
          ],
          isSub: info.isSub, // 返佣金
          sort: info.sort, // 排序
          giveIntegral: info.giveIntegral, // 积分
          isShow: info.isShow,
          isDel: info.isDel,
          sales: info.sales, // 销量
          ficti: info.ficti, // 虚拟销量
          browse: info.browse, // 浏览量
          activity: info.activityStr ? info.activityStr.split(',') : [],
          createDateUTC: this.$moment.utc(res.createDateUTC).tz(this.$moment.tz.guess()).format('YYYY-MM-DD HH:mm:ss') // 创建时间
        }
        if (info.isHot) this.checkboxGroup.isHot = info.isHot
        if (info.isBest) this.checkboxGroup.isBest = info.isBest
        if (info.isNew) this.checkboxGroup.isNew = info.isNew
        if (info.isSeckill) this.checkboxGroup.isSeckill = info.isSeckill
        if (info.isBargain) this.checkboxGroup.isBargain = info.isBargain
        this.productGetRule()
        /* 规格*/
        if (info.specType) {
          this.formValidate.attr = info.attrs.map(item => {
            return {
              attrName: item.attrName,
              attrValue: item.attrValue.split(',')
            };
          });
          this.generateData = true
          this.ManyAttrValue = info.attrValues

          info.attrValues.forEach((item) => {
            const obj = new Object()
            item.suk.split(',').reverse().forEach((subItem, subIndex) => {
              obj['value' + subIndex] = subItem
            })
            Object.assign(item, obj)
          })

          // 把信息整合成一个数组
          const attrValueArray = new Array()

          this.ManyAttrValue.forEach((item, index) => {
            item.image = this.$selfUtil.setDomain(item.image)
            const suk = item.suk.split(',')
            const obj = new Object()
            this.formValidate.attr.forEach((attrItem, attrIndex) => {
              obj[attrItem['attrName']] = suk[attrIndex]
            })
            attrValueArray.push(obj)

            this.attrInfo[Object.values(attrValueArray[index]).sort().join('/')] = item
          })

          const tmp = {}
          const tmpTab = {}

          this.formValidate.attr.forEach((item, index) => {
            tmp['value' + index] = { title: item.attrName }
            tmpTab['value' + index] = ''
          })

          this.manyTabTit = tmp
          this.manyTabDate = tmpTab
          this.formThead = Object.assign({}, this.formThead, tmp)
        } else {
          this.OneattrValue = [info.attrValues || { image: '', marketPrice: 0, price: 0, costPrice: 0, stock: 0, weight: 0, volume: 0 }]
          this.formValidate.attr = []
        }
        /* 规格【end】商品详情：*/

        // 关闭全屏加载框
        this.fullscreenLoading = false
      }).catch(err => {
        this.fullscreenLoading = false
        this.$message.error(err)
      })
    },
    // 点击上一步操作
    handleSubmitUp() {
      if (this.currentTab < 0) this.currentTab = 0
      else this.currentTab = (Number(this.currentTab) - 1).toString()
    },
    // 点击下一步操作
    handleSubmitNest() {
      this.formValidateMethod()
        .then(() => {
          if (Number(this.currentTab) > this.tabPaneVal.length - 1) this.currentTab = (this.tabPaneVal.length - 1)
          else this.currentTab = (Number(this.currentTab) + 1).toString()
        });
    },
    onChangeGroup() {
      this.checkboxGroup.isHot ? this.formValidate.isHot = 1 : this.formValidate.isHot = 0
      this.checkboxGroup.isBest ? this.formValidate.isBest = 1 : this.formValidate.isBest = 0
      this.checkboxGroup.isNew ? this.formValidate.isNew = 1 : this.formValidate.isNew = 0
      this.checkboxGroup.isSeckill ? this.formValidate.isSeckill = 1 : this.formValidate.isSeckill = 0
      this.checkboxGroup.isBargain ? this.formValidate.isBargain = 1 : this.formValidate.isBargain = 0
    },
    // 提交时的数据格式转换
    formValidateConversion(data) {
      const list = new Object()
      if (data.specType) {
        data.attrValue = this.ManyAttrValue.map((item, index) => {
          const { costPrice, image, marketPrice, price, stock, suk, volume, weight } = item
          return { costPrice, image, marketPrice, price, stock, suk, volume, weight }
        })
        for (var i = 0; i < data.attr.length; i++) {
          data.attr[i].attrValues = data.attr[i].attrValue
          delete data.attr[i].attrValue
        }
      } else {
        data.attr = []
        data.attrValue = this.OneattrValue
      }
      list.title = data.storeName
      list.description = data.storeInfo
      list.image = data.image
      list.sliderImage = JSON.parse(JSON.stringify(this.formValidate.sliderImages)).join(',')
      list.cate_Id = data.cateIds.join(',')
      list.unitName = data.unitName
      list.content = this.formatRichText(data.content)
      list.sort = data.sort
      list.sales = data.sales
      list.isHot = data.isHot
      list.isBest = data.isBest
      list.isNew = data.isNew
      list.isShow = data.isShow
      list.isDel = data.isDel
      list.isSeckill = data.isSeckill
      list.isBargain = data.isBargain
      list.giveIntegral = data.giveIntegral
      list.ficti = data.ficti
      list.browse = data.browse
      list.specType = Number(data.specType)
      list.attrs = data.attr
      list.attrValues = data.attrValue
      data.activity.length ? list.activity = data.activity : ''
      return list
    },
    /**
     * 格式化富文本
     * @param html
     * @returns {*}
     */
    formatRichText(html) {
      let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        match = match
          .replace(/style="[^"]+"/gi, "")
          .replace(/style='[^']+'/gi, "");
        match = match
          .replace(/width="[^"]+"/gi, "")
          .replace(/width='[^']+'/gi, "");
        match = match
          .replace(/height="[^"]+"/gi, "")
          .replace(/height='[^']+'/gi, "");
        return match;
      });
      newContent = newContent.replace(
        /style="[^"]+"/gi,
        function (match, capture) {
          match = match
            .replace(/width:[^;]+;/gi, "max-width:100%;")
            .replace(/width:[^;]+;/gi, "max-width:100%;");
          return match;
        }
      );
      newContent = newContent.replace(/<br[^>]*\/>/gi, "");
      newContent = newContent.replace(
        /\<img/gi,
        '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"'
      );
      return newContent;
    },
    // 提交
    handleSubmit(formName) {
      if (this.formValidate.specType && this.formValidate.attr.length === 0) return this.$message.warning('请填写多规格属性!')
      this.onChangeGroup()
      const data = this.formValidateConversion(JSON.parse(JSON.stringify(this.formValidate)))
      this.$refs[formName].validate((valid) => {
        this.fullscreenLoading = true
        if (this.$route.params.id) {
          data.id = this.$route.params.id
          productUpdateApi(data).then(() => {
            this.$message.success('编辑成功!')
            setTimeout(() => {
              this.$router.push({ path: `${this.customRouter}/product/product_list` })
            }, 500)
            this.fullscreenLoading = false
          }).catch(() => {
            this.fullscreenLoading = false
          })
        } else {
          productCreateApi(data).then(() => {
            this.$message.success('新增成功!')
            setTimeout(() => {
              this.$router.push({ path: `${this.customRouter}/product/product_list` })
            }, 500)
            this.fullscreenLoading = false
          }).catch(() => {
            this.fullscreenLoading = false
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scope>
  .iframe {
    width: 344px;
    height: 644px;
    margin: 0 auto;
    border: 1px solid #EEEEEE;
    border-radius: 40px;
    .title {
      width: 100%;
      height: 50px;
      line-height: 50px;
      font-size: 14px;
      text-align: center;
    }
    .content {
      height: 560px;
      overflow: hidden;
      overflow-x: hidden;
      padding: 0 20px;
      overflow-y: auto;
      img {
        max-width: 100%;
      }
    }
  }
  .choiceFormat {
    .el-select {
      .el-input {
        .el-input__inner {
          border-radius: 4px 0 0 4px !important;
        }
      }
    }
    .el-button[type="button"] {
      border-radius: 0 3px 3px 0 !important;
    }
  }
  .upLoadPicBox {
    .coverImg {
      width: 58px;
      height: 58px;
      cursor: pointer;
      img {
        width: 100%;
        height: 100%;
      }
    }
    &.cover-box {
      cursor: auto;
    }
  }

  .subCurLeft {
    margin-left: 0 !important;
  }

  .disLabelmoren{
    .el-form-item__label{
      width: auto !important;
      margin-left: 120px !important;
    }
  }

  .selWidth {
    width: 100%;
  }
  .selWidthd {
    width: 300px;
  }
  .specType {
    .el-form-item__content {
      line-height: 40px;
    }
  }

  .color-item {
    height: 30px;
    line-height: 30px;
    padding: 0 10px;
    color: #ffffff;
    margin-right: 10px;
  }
  .color-list {
    .color-item.blue {
      background-color: #1e9fff;
    }
    .color-item.yellow {
      background-color: rgb(254, 185, 0);
    }
    .color-item.green {
      background-color: #009688;
    }
    .color-item.red {
      background-color: #ed4014;
    }
  }

  .detail {
    .el-form-item__content {
      line-height: normal;
    }
  }
  .el-table {
    .cell {
      padding: 0 10px;
      .box {
        padding: 0 10px;
      }
    }
  }

  .tabNumWidth{
    ::v-deep .el-input-number--medium{
      width: 121px !important;
    }
    ::v-deep .el-input-number__increase{
      width: 20px !important;
      font-size: 12px !important;
    }
    ::v-deep .el-input-number__decrease{
      width: 20px !important;
      font-size: 12px !important;
    }
    ::v-deep .el-input-number--medium .el-input__inner {
      padding-left: 25px !important;
      padding-right: 25px !important;
    }
    ::v-deep thead{
      line-height: normal !important;
    }
    ::v-deep .el-table .cell{
      line-height: normal !important;
    }
  }

  .acea-row {
    .pictrue {
      width: 60px;
      height: 60px;
      border: 1px dotted rgba(0, 0, 0, .1);
      margin-right: 10px;
      position: relative;
      cursor: pointer;
      img {
        width: 100%;
        height: 100%;
      }
      .btndel {
        position: absolute;
        z-index: 1;
        left: 43px;
        top: -8px;
        font-size: 20px;
      }
    }
    .el-icon-circle-close {
      cursor: pointer;
    }
  }

  // 规格添加input框
  .input-new-tag {
    width: 90px;
    margin-right: 10px;
    vertical-align: middle;
  }

  // 规格Tag样式
  .type-tag {
    display: flex;
    align-items: center;
    .scopeType-tag-svg {
      cursor: move;
      svg {
        fill: red;
        font-size: 30px;
      }
    }
    .scopeType-tag {
      .rulesBox {
        display: flex;
        flex-wrap: wrap;
        align-items: self-start;
        .el-tag--light {
          cursor: move;
          padding-left: 30px;
          position: relative;
          &.el-tag--light::after {
            content: " ";
            display: block;
            width: 9px;
            height: 9px;
            border-radius: 50%;
            background-color: #2d8cf0;
            position: absolute;
            top: 8px;
            left: 10px;
          }
          .el-icon-close::before {
            margin-top: 1px;
            margin-right: 1px;
          }
        }
      }
      &.borderStyle{
        width: 90%;
        border: 1px solid #ccc;
        padding: 8px;
        border-radius: 4px;
      }
    }
  }

  // 处理input type = number的上下箭头
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type="number"]{
    -moz-appearance: textfield;
  }

  .boxCard {
    .el-card__header {
      padding-bottom: 0 !important;
      border-bottom: 0 !important;
    }
  }
</style>
